﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using AMS.Inventory.PDA.Castle.DataAccess;
using AMS.Inventory.PDA.Core.DataAccess;
using AMS.Inventory.PDA.Helper;

namespace AMS.Inventory.PDA
{
    public partial class FrmCheckInfo : ScanCodeForm
    {
        public static ArrayList updateMsg = null;
        private readonly CoreDataAccess m_CoreAccess = new CoreDataAccess();
        private readonly string m_PlanId;
        private readonly string m_Username = "";
        private Hashtable _hashtable;
        private SqliteDBServer _sqlDb;
        public string ENABLED = "Enabled";
        private string m_Barcode = ""; //扫描到的条码
        private Control m_control;
        private FormBuilder m_FormBuilder;
        private FormSaver m_Saver;
        public string OLDbARCODE = "OldBarcode", READONLY = "ReadOnly";

        public FrmCheckInfo()
        {
            updateMsg.Clear();
            InitForm();
        }

        public FrmCheckInfo(string username, SqliteDBServer sqliteDbServer, string strPlanId)
        {
            m_PlanId = strPlanId;
            m_Username = username;
            _sqlDb = sqliteDbServer;
            InitForm();
        }

        public FrmCheckInfo(string username, SqliteDBServer sqliteDbServer, string strPlanId, string barcode)
        {
            m_Barcode = barcode;
            m_Username = username;
            m_PlanId = strPlanId;
            _sqlDb = sqliteDbServer;
            InitForm();
        }

        private string SettingXmlPath
        {
            get { return ModCommon.PrjPath + "\\Resources\\BaseDataSet.xml"; }
        }

        private void InitForm()
        {
            if (m_FormBuilder == null)
                m_FormBuilder = new FormBuilder(SettingXmlPath);
            if (m_Saver == null)
                m_Saver = new FormSaver(SettingXmlPath);
            InitializeComponent();

            DataRow row = null;
            try
            {
                row = m_CoreAccess.GetDataRowInventoryInfoByCode(m_Barcode, m_PlanId, m_Username);
            }
            finally
            {
                m_CoreAccess.ConnectedDbClose();
            }
            updateMsg = new ArrayList();
            m_FormBuilder.CreateFormContext(this, 30, row);
            string controlName = m_FormBuilder.OBJ_PRO_HEAD_STRING + "OldBarcode";
            Control c = m_FormBuilder.FindControl(this, controlName);
            if (c.Name == controlName)
            {
                c.KeyUp += OldBarcode_KeyUp;
            }
            m_FormBuilder.SetFormObjInfo(row, this);
        }

        private void FrmCheckInfo_Load(object sender, EventArgs e)
        {
            _hashtable = clsLocalization.ReadContectResource(Name, "ZH");
            clsLocalization.getControlNames(this);
            m_control = m_FormBuilder.FindControl(this, m_FormBuilder.OBJ_PRO_HEAD_STRING + "Name");
            if (!string.IsNullOrEmpty(m_Barcode))
            {
                btnSave.Enabled = true;
                SetConvtorEnabled(true);
                btnUpdate.Enabled = false;
            }
        }

        /// <summary>
        /// 扫描条码事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckInfoFrm_CodeScaned(object sender, CodeScanEventArgs e)
        {
            DataRow row;
            if (!string.IsNullOrEmpty(m_Barcode))
                if (!SaveBarcodeInfo())
                    return;
            m_Barcode = e.barcode.Trim();
            ThrowSound(SoundType.Good);
            try
            {
                row = m_CoreAccess.GetDataRowInventoryInfoByCode(m_Barcode, m_PlanId, m_Username);
                if (row[m_CoreAccess.INVENTORY_STATE].ToString() == m_CoreAccess.ADD &&
                    string.IsNullOrEmpty(row[m_CoreAccess.INVENTORYDATE].ToString()))
                {
                    if (DialogResult.No ==
                        MessageBox.Show(clsLocalization.getFromContentNames(_hashtable, "IsAddAssets"),
                                        ModCommon.MagboxTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                                        MessageBoxDefaultButton.Button1))
                    {
                        m_Barcode = "";
                    }
                    else
                    {
                        row[m_CoreAccess.INVENTORYDATE] = DateTime.Now.ToString(ModCommon.DateFomat);
                        m_FormBuilder.SetFormObjInfo(row, this);
                        SetConvtorEnabled();
                        return;
                    }
                }
            }
            finally
            {
                m_CoreAccess.ConnectedDbClose();
            }
            m_FormBuilder.SetFormObjInfo(row, this);
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(m_Barcode))
            {
                btnSave.Enabled = true;
                SetConvtorEnabled(true);
                btnUpdate.Enabled = false;
            }
        }

        /// <summary>
        /// 设定可以修改值的控件的状态
        /// </summary>
        /// <param name="statu"></param>
        private void SetConvtorEnabled(bool statu)
        {
            Control c;
            bool statuValue;
            foreach (object msg in updateMsg)
            {
                c = m_FormBuilder.FindControl(this, msg.ToString());
                PropertyInfo cp = c.GetType().GetProperty(ENABLED);
                statuValue = statu;
                if (cp == null)
                {
                    cp = c.GetType().GetProperty(READONLY);
                    statuValue = !statu;
                }
                object val;
                val = Convert.ChangeType(statuValue, cp.PropertyType, null);
                cp.SetValue(c, val, null);
            }
        }

        /// <summary>
        /// 获取属性是否有修改
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        private bool SetUpdateStatu(DataRow dr)
        {
            Control control;
            string strVal, columnName;
            bool isUpdate = false;
            foreach (object msg in updateMsg)
            {
                control = m_FormBuilder.FindControl(this, msg.ToString());
                columnName = msg.ToString().Replace(m_FormBuilder.OBJ_PRO_HEAD_STRING, "");
                if (dr.Table.Columns.Contains(columnName))
                {
                    PropertyInfo cp = control.GetType().GetProperty(m_FormBuilder.TEXT);
                    if (cp != null)
                    {
                        strVal = cp.GetValue(control, null).ToString();
                        if (!strVal.Equals(dr[columnName].ToString().Trim()))
                        {
                            isUpdate = true;
                        }
                    }
                }
            }
            return isUpdate;
        }

        /// <summary>
        /// 设定所有控件的可读写状态
        /// </summary>
        private void SetConvtorEnabled()
        {
            bool statuValue = false;
            foreach (object c in Controls)
            {
                PropertyInfo cp = c.GetType().GetProperty(ENABLED);
                statuValue = true;
                if (cp == null)
                {
                    cp = c.GetType().GetProperty(READONLY);
                    statuValue = false;
                }
                object val;
                val = Convert.ChangeType(statuValue, cp.PropertyType, null);
                cp.SetValue(c, val, null);
            }
            btnSave.Enabled = false;
            btnUpdate.Enabled = true;
            m_FormBuilder.FindControl(this, m_FormBuilder.OBJ_PRO_HEAD_STRING + "Barcode").Enabled = false;
        }

        /// <summary>
        /// 保存盘点条码信息
        /// </summary>
        /// <returns></returns>
        private bool SaveBarcodeInfo()
        {
            bool isSave = false;
            string strBarcode = m_FormBuilder.GetObjBarcodeVal(this);

            if (!string.IsNullOrEmpty(strBarcode))
            {
                //m_control = m_FormBuilder.FindControl(this, m_FormBuilder.OBJ_PRO_HEAD_STRING + "Name");
                //if (string.IsNullOrEmpty(m_control.Text.Trim()))
                //return isSave;
                var alErrMsg = new ArrayList();
                try
                {
                    DataRow row = m_CoreAccess.GetDataRowInventoryInfoByCode(strBarcode, m_PlanId, m_Username);
                    if (row == null) throw new NotImplementedException();
                    bool isUpdate = false;
                    if (btnSave.Enabled)
                    {
                        isUpdate = SetUpdateStatu(row) &&
                                   row[m_CoreAccess.INVENTORY_STATE].ToString() == m_CoreAccess.MATCH;
                    }
                    m_Saver.SetObjDataRow(row, this, ref alErrMsg);
                    if (alErrMsg != null && alErrMsg.Count > 0)
                    {
                        var sbErr = new StringBuilder();
                        foreach (string str in alErrMsg)
                        {
                            sbErr.Append(str + "\r\n");
                        }
                        MessageBox.Show(sbErr.ToString());
                        return false;
                    }
                    else
                    {
                        if (isUpdate)
                            row[m_CoreAccess.INVENTORY_STATE] = m_CoreAccess.UPDATED;
                        m_CoreAccess.SaveDataRowToInventoryInfo(row, "Id", m_PlanId);
                        m_Barcode = "";
                        isSave = true;
                        btnSave.Enabled = false;
                        btnUpdate.Enabled = true;
                    }
                }
                finally
                {
                    m_CoreAccess.ConnectedDbClose();
                }
            }
            return isSave;
        }


        private void btnSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(m_Barcode))
                return;
            if (SaveBarcodeInfo())
            {
                MessageBox.Show(clsLocalization.getFromContentNames(_hashtable, "SuccessUpdate"), ModCommon.MagboxTitle);
                SetConvtorEnabled(false);
                btnSave.Enabled = false;
                btnUpdate.Enabled = true;
               DataRow row = m_CoreAccess.GetDataRowInventoryInfoByCode("", m_PlanId, m_Username);
                m_FormBuilder.SetFormObjInfo(row, this);
            }
        }

        private void FrmCheckInfo_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.KeyCode == Keys.Up))
            {
                // Up
                SelectNextControl(this, true, true, false, true);
            }
            if ((e.KeyCode == Keys.Down))
            {
                // Down
                SelectNextControl(this, true, true, true, true);
            }
        }

        public void OldBarcode_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                DataRow row;
                if (!string.IsNullOrEmpty(m_Barcode))
                    if (!SaveBarcodeInfo())
                        return;
                string controlName = m_FormBuilder.OBJ_PRO_HEAD_STRING + "OldBarcode";
                Control c = m_FormBuilder.FindControl(this, controlName);
                m_Barcode = c.Text.Trim();
                try
                {
                    row = m_CoreAccess.GetDataRowInventoryInfoByCode(m_Barcode, m_PlanId, m_Username);
                    row[OLDbARCODE] = m_Barcode;
                    if (row[m_CoreAccess.INVENTORY_STATE].ToString() == "Add" &&
                        string.IsNullOrEmpty(row[m_CoreAccess.INVENTORYDATE].ToString()))
                    {
                        if (DialogResult.No ==
                            MessageBox.Show(clsLocalization.getFromContentNames(_hashtable, "IsAddAssets"),
                                            ModCommon.MagboxTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                                            MessageBoxDefaultButton.Button1))
                        {
                            m_Barcode = "";
                        }
                        else
                        {
                            row[m_CoreAccess.INVENTORYDATE] = DateTime.Now.ToString(ModCommon.DateFomat);
                            m_FormBuilder.SetFormObjInfo(row, this);
                            SetConvtorEnabled();
                            return;
                        }
                    }
                }
                finally
                {
                    m_CoreAccess.ConnectedDbClose();
                }
                m_FormBuilder.SetFormObjInfo(row, this);
            }
        }

        private void FrmCheckInfo_Closing(object sender, CancelEventArgs e)
        {
            if (!string.IsNullOrEmpty(m_Barcode))
            {
                SaveBarcodeInfo();
            }
        }
    }
}